'''
文件IO流程：
1、打开文件，创建文件对象
    open函数打开文件或创建对象
    open(file_name, mode="r", encoding=None)
mode:
    1、r   读取模式（字符串）  rb 读取（字节）
    2、w   写入模式（覆盖），打开的话会将文件的内容覆盖为空
    3、a   追加
    4、r+  读写模式打开
2、读写
3、关闭文件
encoding= 指定字符集
'''
file_name = r'D:\PythonProject\python-learn\operation_document\/test1.txt'
# do = open(file_name, mode="r")
# file_01 = do.read()
# print(file_01)
# do.close()#关闭文件


# ------------遍历文件------------
# with的好处时可以自动关闭文件
# with open(file_name, mode="r")as do:
#     for i in do:
#         print("每一行内容：%s" % i)
# print("文件是否关闭 %s" % do.closed)

# -----------IP地址统计-----------------
access_log = r'D:\PythonProject\python-learn\operation_document\access_log'
def log():
    client_ip_access = []
    with open(access_log, mode="r", encoding='UTF-8') as access_log_http:
        for line in access_log_http:
            client_ip = line.split()[0]
            client_ip_access.append(client_ip)
    for ip in set(client_ip_access):
        if client_ip_access.count(ip) < 10:
            continue
        else:
            print("客户端地址： %s, 访客次数: %s" % (ip, client_ip_access.count(ip)))



def webRegex(): #使用正则表达式来匹配IP地址
    import re
    client_ip_access = []
    #
    ip_pattern = r'\b(?:\d{1,3}\.){3}\d{1,3}\b'
    with open(access_log, mode="r", encoding='UTF-8') as access_log_http:
        for line in access_log_http:
            ip_addresses = re.search(ip_pattern, line)
            if ip_addresses:
                ip_client = ip_addresses.group()
                client_ip_access.append(ip_client)
    for ip in set(client_ip_access):
        if client_ip_access.count(ip) < 10:
            continue
        else:
            print("客户端地址： %s, 访客次数: %s" % (ip, client_ip_access.count(ip)))


print("--------文件的写入模式-主要适用于新建文件----------------------------------")
# 持久化存储
# new_file = r"D:/PythonProject/python-learn/operation_document/file_01.txt"
# open(new_file, mode="wb")

# 替换文件的内容
# 创建一个临时文件、将修改后的数据写入临时文件
# 然后将临时文件覆盖掉要修改的文件，之后再将临时文件删除
def replace_redis_to_mysql():
    #创建一个临时文件
    file_name1 = r'D:/PythonProject/python-learn/operation_document/file_01.txt'
    file_obj = open(file_name1, mode="w")
    file_old_name = r'D:\PythonProject\python-learn\operation_document\test1.txt'
    with open(file_old_name, mode="r") as fobj:
        for line in fobj:
            if "redis" in line:
                new_line = line.replace("redis", "mysql")
                file_obj.write(new_line)
            else:
                file_obj.write(line)

    file_obj.close()# 关闭临时文件夹
    import os
    import shutil
    shutil.copy(file_name1,file_old_name)
    os.remove(file_name1)

# if __name__ == '__main__':
#     replace_redis_to_mysql()

print("----------控制光标移动，文件的必须以字节的方式打开------------------")
# tell(),返回光标的位置
'''
seek(a,b)
    a: 正数：光标向前移动；负数：光标向后移动
    b:
        0  将光标移动到文件开始处
        1  保持当前位置不动
        2  将光标移动到文件末尾处
        
'''

file = r"D:\PythonProject\python-learn\operation_document\test1.txt"
with open(file, mode="rb") as fobj:
    print("光标位置：%s" % fobj.tell())
    content_01 = fobj.read()
    print(content_01)
    print("光标位置：%s" % fobj.tell())

    fobj.seek(0,2)
    print("光标位置：%s" % fobj.tell())

    fobj.seek(-5,2)
    content_02 = fobj.read()
    print(content_02)

print("-----------实时跟踪文件输出------------------")
# 打开文件记录一个文件的初始位置
import time
def Jiankong_file():
    file = r"D:\PythonProject\python-learn\operation_document\test1.txt"
    file_name01 = open(file, mode="rb")
    file_name01.seek(0,2)
    old_position = file_name01.tell()

    while True:
        file_name01.seek(0,2)
        new_position = file_name01.tell()
        if new_position > old_position:
            file_name01.seek(old_position - new_position,2)
            print(file_name01.read())
            old_position = new_position
        time.sleep(6)
if __name__ == '__main__':
    Jiankong_file()